import argparse
import pandas as pd

def extract_peripheral_fields(xlsx, sheet, regname=None, out=None):
    # Read the Excel file
    df = pd.read_excel(xlsx, sheet_name=sheet)

    # Check if 'name' and 'resetValue' columns exist
    if 'name' not in df.columns:
        raise ValueError(f"Column 'name' not found in sheet '{sheet}'")
    if 'resetValue' not in df.columns:
        raise ValueError(f"Column 'resetValue' not found in sheet '{sheet}'")

    # Find the index of 'name' and 'resetValue' columns
    name_col_index = df.columns.get_loc('name')
    reset_value_col_index = df.columns.get_loc('resetValue')

    # Define reserved_list and fields list
    reserved_list = ["reserved", "reserve", "r_"]
    fields = []

    # Filter rows based on regname if specified
    if regname:
        filtered_df = df[df['name'] == regname]
    else:
        filtered_df = df[df['name'].notna()]

    # Iterate through each row in the filtered DataFrame
    for _, row in filtered_df.iterrows():
        # Iterate through cells from 'name' column to 'resetValue' column
        for col_index in range(name_col_index + 1, reset_value_col_index):
            cell_value = str(row.iloc[col_index])
            if cell_value.lower() not in reserved_list and cell_value not in fields:
                fields.append(cell_value)

    # Create a new DataFrame with the extracted fields
    new_data = {'name': fields}
    new_df = pd.DataFrame(new_data)

    # Add empty columns for access, description, headerEnumName, enumValueName, enumValue, enumDescription
    new_columns = ['access', 'description', 'headerEnumName', 'enumValueName', 'enumValue', 'enumDescription']
    for col in new_columns:
        new_df[col] = ''

    # Save the new DataFrame to an Excel file
    if out is None:
        if regname:
            out = xlsx.replace('.xlsx', f'_{sheet}_{regname}_out.xlsx')
        else:
            out = xlsx.replace('.xlsx', f'_{sheet}_all_out.xlsx')
    new_df.to_excel(out, index=False)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Extract peripheral fields from an Excel file.')
    parser.add_argument('--xlsx', required=True, help='Input Excel file path')
    parser.add_argument('--sheet', required=True, help='Sheet name to process')
    parser.add_argument('--regname', default=None, help='Optional register name to filter by')
    parser.add_argument('--out', default=None, help='Optional output file path')

    args = parser.parse_args()

    try:
        extract_peripheral_fields(args.xlsx, args.sheet, args.regname, args.out)
    except Exception as e:
        print(f"An error occurred: {e}")



